package plugins

import (
	"errors"
	"fmt"
	"html/template"
	"io/fs"
	"os"
	"os/exec"
	"strings"
)

type ShellPlugin struct {
	BasePlugin
}

func (self *ShellPlugin) Run() (err error) {
	step := self.Steps[self.Index]

	self.Running()
	prefix := fmt.Sprintf("%03d-%s", self.Index, step.Name)

	// TODO
	err = os.WriteFile(fmt.Sprintf("%s.input.txt", prefix), []byte{}, fs.ModePerm)
	if err != nil {
		self.Error()
		panic(err)
	}
	template_file := fmt.Sprintf("%s_shell.sh.tpl", prefix)
	dst_file := fmt.Sprintf("%s_shell.sh", prefix)
	if len(step.Code) != 0 {
		var buffer strings.Builder
		err = os.WriteFile(template_file, []byte(step.Code), fs.ModePerm)
		if err != nil {
			self.Error()
			panic(err)
		}

		t, err := template.ParseFiles(template_file)
		if err != nil {
			self.Error()
			panic(err)
		}

		fmt.Println(self.RenderParams())

		t.Execute(&buffer, self.RenderParams())

		err = os.WriteFile(dst_file, []byte(buffer.String()), fs.ModePerm)
		if err != nil {
			self.Error()
			panic(err)
		}
	} else {
		self.Error()
		panic(errors.New("shell节点必须包含Code"))
	}

	cmd := exec.Command("bash", dst_file)
	out, err := cmd.CombinedOutput()
	if err != nil {
		self.Error()
		panic(err)
	}

	err = os.WriteFile(fmt.Sprintf("%s.output.txt", prefix), out, fs.ModePerm)
	if err != nil {
		self.Error()
		panic(err)
	}

	self.UpdateOutput(string(out))
	self.Finish()
	return nil
}
